<template>
  <base-breadcrumb>
    <a-radio-group v-model="btnVal" @change="onChange()">
      <a-radio-button :value="0">所有</a-radio-button>
      <a-radio-button value="RECTIFICATION">待整改</a-radio-button>
      <a-radio-button value="REVIEW">待复查</a-radio-button>
      <a-radio-button value="REVIEWPAST">复查通过</a-radio-button>
      <a-radio-button value="QUALIFIED">合格</a-radio-button>
      <a-radio-button value="UNQUALIFED">不合格不整改</a-radio-button>
    </a-radio-group>

    <!-- 搜索 -->
    <searchData v-if="btnVal === 0" :searchData="searchArr" @search2="search" />
    <!-- 表格 -->
    <a-card id="tableBox" :bordered="false">
      <a-button v-btn-permission="'hse_001_zgd_06'" type="primary" :disabled="!canDownLoad" class="mb20" v-if="hideBuquBtn()"
                @click="generateNotice"
      >生成整改通知单
      </a-button>
      <!-- 汇总 -->
      <collapseStatic
        v-if="btnVal === 0"
        :columnsSummary="columnsSummary"
        @switchSummary="switchSummary"
        :tabList="tabList"
        :form="summaryParam"
        :loadCount="loadCount"
        :loadDataSummaryApi="api"
      >
        <template #left="scoped">
          <span>已选择<a><b> {{ selectLength || 0 }}</b></a>，</span> 
          <span>检查记录数<a><b>{{ scoped.data.total || 0 }}</b></a>，</span>
          <span>合格数<a><b>{{ scoped.data.qualifiedNum || 0 }}</b></a>，</span>
          <span>不合格数<a><b>{{ scoped.data.unQualifiedNum || 0 }}</b></a>，</span>
          <span>合格率<a><b>{{ scoped.data.qualifiedRate || '0%' }}</b></a></span>
        </template>
      </collapseStatic>
      <div class="pub-table-select-count" v-else>
          <a-icon type="info-circle" theme="twoTone"/>
          已选择<b style="color: #40a9ff;"> {{ selectLength || 0 }}，</b>
          <span style="padding-right: 10px;">
            总计<b  style="color: #40a9ff;margin-left:5px">{{total || 0}}</b>
          </span>
        </div>
      <list-table
        ref="table"
        :columns="columns"
        :request="loadData"
        :selectConfig="{use: true, type: 'checkbox',rowKey: 'id' }"
        @select-click="selectClick"
      >
        <span slot="sort" slot-scope="text, record, index">{{ index + 1 }}</span>
        <template slot="action" slot-scope="text, record">
          <div class="pub-table-list-action">
            <span v-btn-permission="'hse_001_loo_04'" @click="handleManage(record, 'look')">查看</span>
            <span v-btn-permission="'hse_001_del_03'" @click="handleDelete(record)" v-if="hideBuquBtn()">删除</span>
            <a-tooltip>
                <template slot="title">{{ `${record.modelId ? '已' : '未'}关联BIM模型` }}</template>
                <a-icon @click.stop="handleRelease(record)" type="link" :style="{ color: record.modelId ? '#1890ff' : '#ccc' }" />
              </a-tooltip>
          </div>
        </template>
      </list-table>
    </a-card>
      <!-- 关联BIM模型弹窗 -->
  <BimRelease ref="bimRelease" :zIndex="1002" :destroyOnClose="true" :isRelease="false" :visible.sync="bimVisible" :modelList="modelList" :highLightList="highLightList"/>
  </base-breadcrumb>
</template>

<script>
import CollapseStatic from '@/views/quality/components/CollapseStatic' // 汇总
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目名称
import OrgTreeSelect from '@/components/OrgTreeSelect'
import SelectSubcontractor from '@/components/Select/SelectSubcontractor'
import BSelect from '@/components/BComponents/BSelect'
import Api from '@/api/office/hazardIdentification'
import SelectTreeCommon from '@/components/Select/SelectTreeCommon'
import request2 from '@/utils/request2'
import LApi from '@/api/safetySupervision/checkAndRectify/checkRecord'
import rectifyNoticeApi from '@/api/safetySupervision/checkAndRectify/rectifyNotice'
import BimRelease from '@/components/Dialog/BimRelease' // BIM模型关联

export default {
  name: 'a' + Date.now(),
  components: {
    CollapseStatic,
    BimRelease
  },
  data() {
    return {
      searchArr: [
        // { name: '所属分公司', type: SelectSubCompany, valueKey: 'branchComId' },
        {
          name: '所属单位',
          valueKey: 'searchQuery',
          type: OrgTreeSelect,
        },
        // { name: '所属项目', type: SelectProject, valueKey: 'projectId', keyValue: 'branchComId' },
        { name: '责任分包单位', keyValue: 'searchQuery._checked', valueKey: 'subcontractorId', type: SelectSubcontractor },
        {
          name: '检查结果', valueKey: 'safetyAuditStatusEnum', type: BSelect, data: [], list: [
            { id: 'REVIEW', name: '待复查' },
            { id: 'REVIEWPAST', name: '复查通过' },
            { id: 'REVIEWNOPAST', name: '复查未通过' },
            { id: 'UNQUALIFED', name: '不合格不整改' },
            { id: 'UNQUALIFEDRECTIFICATION', name: '不合格需整改' },
            // { id: 'RECTIFICATION', name: '待整改' },
            { id: 'QUALIFIED', name: '合格' },
            { id: 'UNQUALIFEDS', name: '不合格' }
          ]
        },
        {
          name: '超时状态', valueKey: 'timeoutStatus', type: BSelect, data: [], list: [
            { id: 0, name: '超时' },
            { id: 1, name: '不超时' }
          ]
        },
        {
          name: '检查区域', valueKey: 'respAreaId', keyValue: 'searchQuery._checked', type: SelectTreeCommon,
          params: { sources: 0 },
          linkParamsKey: 'id',
          api: e => Api.subPackArea({}, e)
        },
        {
          name: '检查类型', valueKey: 'typeId', type: BSelect,
          request: async () => {
            let res = await request2({
              url: '/cscec-quality-business/quality/types-label',
              params: { type: '0', code: '0' }
            })
            if (res.code === this.SUCCESS_CODE) {
              return { code: this.SUCCESS_CODE, data: res.data.filter(v => v.enabled) }
            }
            return { code: this.SUCCESS_CODE, data: [] }
          }
        },
        {
          name: '问题级别', value: 'securityControlEnum', type: 'select', data: [
            { label: '优秀(合格)', value: 'EXCELLENT' },
            { label: '良好(合格)', value: 'WELL' },
            { label: '一般(合格)', value: 'GENERAL' },
            { label: '轻微(不合格)', value: 'SLIGHT' },
            { label: '一般(不合格)', value: 'ORDINARY' },
            { label: '严重(不合格)', value: 'SERIOUS' }
          ]
        },
        {
          name: '隐患类型', valueKey: 'treeLabelId', type: SelectTreeCommon,
          needLink: false,
          api: async () => {
            let res = await request2({ url: 'cscec-pms-app-business/safety/getLabelTypesLeft/HIDDEN_DANGERS_LEFT' })
            if (res.code === this.SUCCESS_CODE) {
              return { code: this.SUCCESS_CODE, data: [res.data] }
            }
            return { code: this.SUCCESS_CODE, data: [] }
          }
        },
        { name: '检查人', value: 'checkPeople', type: 'input' },
        {
          name: '检查时间',
          value: 'createTime',
          type: 'dateRange',
          attr: {
            rangeFormat: ['createTimeStart', 'createTimeEnd']
          }

        },
        { name: '复查人', value: 'reviewUserName', type: 'input' },
        { name: '整改人', value: 'rectificationUserName', type: 'input' }
      ],
      columns: [
        { title: '序号', dataIndex: 'sort', width: 70, scopedSlots: { customRender: 'sort' } },
        { title: '分公司名称', dataIndex: 'branchComName', width: 140 },
        { title: '项目名称', ellipsis: true, dataIndex: 'projectName', width: 140 },
        { title: '检查区域', dataIndex: 'respAreaStr', width: 250 },
        {
          title: '检查类型', dataIndex: 'typeName', width: 150, customRender: (text, row, index) => {
            let list = []
            if (text) {
              list = text.split(',')
            }
            return <div>
              {list.map(v => {
                return <div>{v}</div>
              })}
            </div>
          }
        },
        { title: '问题等级', dataIndex: 'securityControlEnumStr', width: 100 },
        { title: '隐患类型', dataIndex: 'treeLabelStr', width: 150 },
        { title: '检查人', dataIndex: 'creatorName', width: 120 },
        { title: '检查时间', dataIndex: 'createTime', width: 200 },
        { title: '复查人', dataIndex: 'reviewUserName', width: 120 },
        { title: '责任分包单位', dataIndex: 'subcontractorName', width: 250 },
        { title: '整改人', dataIndex: 'rectificationUserName', width: 120 },
        { title: '整改期限', dataIndex: 'rectificationTime', width: 200 },
        {
          title: '状态', dataIndex: 'safetyAuditStatusEnumStr', width: 130,
          customRender: (text, row, index) => {
            if (row.safetyAuditStatusEnumStr === '待整改' && row.isBeyond == '1') {
              return '超期未整改'
            }
            return row.safetyAuditStatusEnumStr
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 150,
          fixed: 'right',
          scopedSlots: { customRender: 'action' }
        }
      ],
      btnVal: 0,
      selectLength:0,
      total:0,
      queryParam: {}, // 查询参数
      summaryParam: {},
      columnsSummary: [
        {
          title: '检查类型',
          dataIndex: 'name',
          ellipsis: true
        },
        {
          title: '检查总数',
          dataIndex: 'total',
          ellipsis: true
        },
        {
          title: '合格数',
          dataIndex: 'qualifiedNum'
        },
        {
          title: '不合格数',
          dataIndex: 'unQualifiedNum'
        },
        {
          title: '合格率',
          dataIndex: 'qualifiedRate'
        }
      ], // 汇总表头
      tabList: [
        { key: '-1', name: '全部' },
        { key: '0', name: '本周' },
        { key: '1', name: '本月' },
        { key: '2', name: '本年' }
      ], // 汇总标题
      loadData: (parameter) => {
        const q = Object.assign({}, parameter, { query: this.queryParam })
        if (this.btnVal !== 0) {
          q.query.safetyAuditStatusEnum = this.btnVal
        }
        if (q.query.createTimeStart) q.query.createTimeStart = q.query.createTimeStart + ' 00:00:00'
        if (q.query.createTimeEnd) q.query.createTimeEnd = q.query.createTimeEnd + ' 23:59:59'
        this.summaryParam = { ...q.query, pageNo: q.pageNo, pageSize: q.pageSize }
        return LApi.findListByMainPc({}, q).then((res)=>{
          this.total = res.totalSize;
          return res
        })
      },
      loadCount: 0,
      api: LApi,
      // api:checkRecord,
      canDownLoad: false,
      selectRows: [],
      bimVisible:false,
      modelList: [],
      highLightList:'',
    }
  },
  methods: {
      /**
    * @description: 查看关联的BIM模型
     * @param {*} record：业务对象
     * @return {*}
     */
     handleRelease(record) {
      if (record.modelId) {
        this.modelList = [{ id: record.modelId, modelId: record.modelFileId, version: record.modelFileVersion,
          modelTitle: record.modelTitle, uuId: [record.bimId?.split('&&&&')?.[1]], subAreaId: record.subAreaId }];
        this.highLightList = record.bimId?.split('&&&&')?.[0];
        this.bimVisible = true
      }
    },
    switchSummary(e) {
      // console.log(e)
      this.selectRows = []
      this.canDownLoad = false
      // this.queryParam.type = e
      // this.$refs.table.refresh()
    },
    selectClick(e) {
      this.selectLength = e.rows.length;
      if (!e.rows.length) return this.canDownLoad = false
      // console.log(e.rows.map(v => v.subcontractorName))
      let projectId = e.rows[0].projectId
      let subcontractorId = e.rows[0].subcontractorId
      for (let i = 1; i < e.rows.length; i++) {
        if (e.rows[i].projectId !== projectId ||e.rows[i].subcontractorId !== subcontractorId) {
          return this.canDownLoad = false
        }
      }
      this.selectRows = e.rows
      this.canDownLoad = true
    },
    async generateNotice() {
      this.$submitConfirm(async () => {
        let data = {
          ids: this.selectRows.map(v => v.id),
          ...this.selectRows[0]
        }
        delete data.id
        let res = await rectifyNoticeApi.createByMain({}, data)
        if (res.code === this.SUCCESS_CODE) {
          this.selectRows = []
          this.canDownLoad = false
          this.$refs.table.refresh()
          this.$noticeSuccess('整改通知单已生成，可到整改通知单查看。')
        }
      }, '确认生成整改通知单？')
    },
    onChange() {
      this.total = 0
      this.selectLength = 0;
      this.selectRows = []
      this.canDownLoad = false
      this.queryParam = {}
      this.$refs.table.refresh()
    },
    /**
     * 搜索
     */
    search(value) {
      value && (this.queryParam = value)
      this.$refs.table.refresh()
      this.loadCount++
    },
    /**
     * 操作栏
     */
    handleManage(record, pageType) {
      this.$router.push({
        path: '/safetySupervision/checkAndRectify/checkRecord/detail',
        query: {
          id: record.id,
          pageType
        }
      })
    },
    /**
     * 删除记录
     */
    handleDelete(e) {
      if (e.typeName.includes('外部检查')){
        // if (e.typeName.includes('日巡查')){
        return this.$noticeWarning('外部检查不能被删除')
      }

      this.$delList3(LApi.del, () => {
        this.search()
      }, { id: e.id })
    }
  }
}
</script>


